<template>
  <div :class="$style.wrap">
    <Button v-if="showBtn" type="primary" @click="clickHandle">话机放音</Button>
    <Dialog :visible.sync="visible" title="话机放音" :close-on-click-modal="false" @closed="closeHandle">
      <Button type="primary" @click="playHandle">{{ play?'停止':'播放' }}</Button>
      <Button type="primary" :disabled="!play" @click="pauseHandle">{{ !pause?'暂停':'恢复' }}</Button>
      <Button type="primary" :disabled="!play||pause" @click="beforFastHandle">快进</Button>
      <Button type="primary" :disabled="!play||pause" @click="backFastHandle">快退</Button>
    </Dialog>
  </div>
</template>
<script>
import Dialog from '@/components/Dialog'
export default {
  name: 'PhonePlay',
  components: {
    Dialog
  },
  props: {
    voice: {
      type: Object,
      default: () => ({})
    },
    stepTime: {
      type: Number,
      default: 5
    },
    showBtn: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      play: false,
      visible: false,
      pause: false
    }
  },
  created() {
    this.regEvent()
  },
  beforeDestroy() {
    this.regEvent('off')
  },
  methods: {
    // 开始播放
    startPlay() {
      this.play = true
    },
    stopPlay() {
      this.play = false
    },
    // 暂停恢复相关
    pausePlay() {
      this.pause = true
    },
    continuePlay() {
      this.pause = false
    },
    // 播放完毕
    releaseHandle() {
      this.play = false
      this.pause = false
    },
    // 事件注册
    regEvent(name = 'on') {
      // 注册事件 OnStartPlaySuccess OnStopPlaySuccess OnSayFreeSuccess
      // OnPausePlaySuccess OnContinuePlaySuccess
      this.$cps[name]('OnStartPlaySuccess', this.startPlay)
      this.$cps[name]('OnStopPlaySuccess', this.stopPlay)
      this.$cps[name]('OnPausePlaySuccess', this.pausePlay)
      this.$cps[name]('OnContinuePlaySuccess', this.continuePlay)
      this.$cps[name]('OnSayFreeSuccess', this.releaseHandle)
    },
    // 开始，停止放音
    playHandle() {
      if (!this.play) {
        return this.$cps.beginPlay(this.voice.recordingAddress)
      } else {
        return this.$cps.stopPlay()
      }
    },
    // 暂停、恢复放音
    pauseHandle() {
      if (!this.pause) {
        return this.$cps.pausePlay()
      } else {
        return this.$cps.resumePlay()
      }
    },
    // 快进
    beforFastHandle() {
      return this.$cps.foreFastPlay(this.stepTime)
    },
    // 快退
    backFastHandle() {
      return this.$cps.backFastPlay(this.stepTime)
    },
    closeHandle() {
      if (this.play) {
        this.playHandle()
      }
      this.$emit('closed')
      this.play = false
      this.pause = false
    },
    clickHandle() {
      if (!this.voice.recordingAddress) {
        this.$message.error('没有录音文件！')
      } else {
        this.visible = true
      }
    }
  }
}
</script>
<style lang='scss' module>
.wrap{
  display: inline-block;
  text-align: left;
}
</style>
